//宫格
import uniGrid from "/uni_modules/uni-grid/components/uni-grid/uni-grid.vue";
// 公共头部
import myHeader from "/pages/headerfoot/pages/header.vue";
// 基础方法
import Base from "/common/base.js";
//语言
import langMatch from '/utils/langmatch.js';
//cache缓存
import Cache from '@/utils/cache.js';
//打帮赛方法
import hitmatchcommon from '@/common/hitmatchcommon.js';

export default {
	props: {
		code: String,
		project_make_id: String,
		project_id: String,
		gametype: String,
		initiator: String
	},
	components: {
		myHeader,
		uniGrid,
	},
	data() {
		return {
			grade: 1, //等级
			numberarr: [], //数组
			first: 1, //第一个
			proportion: 0, //比例
			langMatch: langMatch.lang, //语言1
			censorship: [], //已经测试关卡
			level_data: {},//等级
			times: 0, //分钟
			seconds: '00', //秒

			timer: {}, //时间
			ifshow: true, //是否显示
			// score: 2, //获取分数
			ifpass: false, //是否弹出闯关界面:false=不弹出，true=弹出
			btn: [],
			btna: ['继续下一题', '返回关卡列表', '返回项目选择', '查看排行榜', '再次打榜','提交分数'],
			btnb: ['立即进入下一关', '返回关卡列表', '返回项目选择', '查看排行榜', '再次打榜','提交分数'],
			btnc: ['', '返回关卡列表', '返回项目选择', '查看排行榜', '再次打榜','提交分数'],

			passTheResult: ['闯关成功', '闯关失败'],
			passtitle: '',
			ifgame: true, //是否点击列表开始游戏

			nowfrequency: 1, //通关总数
			thisLeveltime: 0, //本关用时
			fraction: 0, //本题得分
			thisLevelfraction: 0, //本关得分
			successnumberarr:[],//问题
			coding:0,//编码
			project_user_achievement_end:0, //提交分数 0=未提交 1=提交
		}
	},
	mounted() {
		var that = this;
		console.log(that.gametype);//对战类型
		console.log(that.initiator);//发起人
		
		//console.log(that.code);//编码
		if(that.code){
			that.coding=that.code;
		}
		//console.log(that.project_make_id);//赛事
		if(that.project_make_id){
			Cache.set('project_make_id',that.project_make_id)
		}
		//console.log(that.project_id);//项目
		if(that.project_id){
			Cache.set('project_id',that.project_id)
		}
		
		that.getMakeProjecParameter(); //得到项目配置
	
	},
	methods: {
		//选择游戏等级
		selectgame(e) {
			var that = this;
			that.numberarr=[]; //数组
			that.grade = e; //重新赋值等级
			if(!that.coding){
				that.coding=new Date().getTime();//设置编码
			}
			//次数判断
			that.orderJudgment();

			var gongGrid = that.level_data[that.grade];

			var grade = parseInt(gongGrid['num']);
			for (var i = 1; i <= (grade * grade - 1); i++) {
				that.successnumberarr.push(i);
				that.numberarr.push(i);
			}
			that.numberarr = Base.shuffle(that.numberarr);

			that.proportion = parseFloat(100 / grade - 1); //比例

			while (Base.ifsolution(that.numberarr) == false) { //为false 重新执行方法 直到为true 时跳出循环
				that.numberarr = Base.shuffle(that.numberarr); //更新表达式
			}
			that.ifgame = false; //开始游戏
			//赋值0
			that.numberarr.push(0);
		},

		//得到项目配置
		async getMakeProjecParameter() {
			var that = this;
			var data = {};
			data['project_id'] = Cache.get('project_id');
			data['make_user_id'] = Cache.get('user_id');
			data['make_id'] = Cache.get('project_make_id');
			console.log(data);
			hitmatchcommon.getMakeProjecParameterLibMethod(data).then(res => {
				if (res) {
					 that.level_data = res.make_project_parameter_list;
				}
			});
		},

		//开始游戏
		startGame() {
			var that = this;
			that.ifshow = false; //隐藏弹出遮罩
			that.times = that.level_data[that.grade]['min_time']; //获取时间
			that.countdown(); //计算器
		},
		//倒计时
		countdown() {
			var that = this;
			var times = parseInt(that.times); //分钟
			var seconds = parseInt(that.seconds); //秒
			that.timer = setInterval(() => {
				that.thisLeveltime++; //本题答题用时
				if (seconds <= 0) {
					if (times > 0) {
						that.seconds = seconds = 59;
						that.times = --times; //减分钟
					} else {
						that.submit(); //提交
						//时间结束1
						clearInterval(that.timer)
					}
				} else {
					--seconds; //减秒数
					if (seconds <= 9) {
						that.seconds = '0' + seconds;
					} else {
						that.seconds = seconds;
					}
				}
			}, 1000);
		},
		//计算分数
		calculateTheScore() {
			var that = this;
			var calculateBaseScore = 0; //分数
			var scorePerQuestion = that.level_data[that.grade]['scorePerQuestion']; //每题分数
			var ifQuestionScore = that.level_data[that.grade]['ifQuestionScore']; //是否计算每题分数 1=-否 2=是
			calculateBaseScore = that.getcalculateBaseScore(); //基础分数
			//每题分数并顺序不正确
			if (ifQuestionScore == '2' &&  !that.ranked()) {
				//判断顺序加法
				calculateBaseScore =parseFloat(that.judgmentOrderAddition(scorePerQuestion)); //每题分数
			}
			that.fraction = calculateBaseScore; // 本题分数
			that.thisLevelfraction = parseFloat(that.fraction) + parseFloat(that.thisLevelfraction); // 本关分数
			//顺序是否正确
			that.passtitle = that.passTheResult[0]; //默认闯关失败
			if (!that.ranked()) {
				that.passtitle = that.passTheResult[1]; //默认闯关成功
				that.btn = that.btnc; //再次打榜
			}
		},
		//判断顺序加法
		judgmentOrderAddition(scorePerQuestion) {
			var that = this;
			var p = 1;
			var scoreQuestion = that.determineTheNumberOfCorrectOrders(); //顺序是否正确与返回个数
			scoreQuestion = parseFloat(scorePerQuestion) * parseFloat(scoreQuestion);
			return scoreQuestion; //返回分数
		},
		//基础分数
		getcalculateBaseScore() {
			var that = this;
			var calculateBaseScore = 0;
			var totalTime = parseFloat(that.level_data[that.grade]['min_time']) * 60; //最低分钟时间
			var baseScore = that.level_data[that.grade]['baseScore']; //获取基础分数
			var fractionsPerSecond= that.level_data[that.grade]['fractionsPerSecond']; //每一秒分数
			//顺序是否正确
			if (that.ranked()) {
				 calculateBaseScore = parseFloat(baseScore) +( parseFloat(totalTime) -  parseFloat(that.thisLeveltime))* parseFloat(fractionsPerSecond) //基础分数 
			}
			return calculateBaseScore;
		},
		//提交数据
		submit() {
			var that = this;
			//测试次数加1
			that.nowfrequency++;
			//时间结束
			clearInterval(that.timer)
			//计算分数
			that.calculateTheScore();

			var that = this;
			var data = {};
			var clearance=0
			if (that.ranked()) {
				clearance = 1;
			}
			data['project_id'] = Cache.get('project_id');
			data['make_user_id'] = Cache.get('user_id');
			data['make_id'] = Cache.get('project_make_id');
			data['questions_answer'] = that.successnumberarr; //问题
			data['my_answer'] = that.numberarr; //我的答案
			data['answertime'] =that.thisLeveltime; //答题用时
			data['allscore'] = that.thisLevelfraction; //我的分数
			data['level'] = that.grade; //关卡
			data['clearance'] = clearance; //是否过关
			data['topic'] = that.nowfrequency; //题数
			
			data['make_project_user_code'] = that.coding; //编码
			data['project_user_achievement_end'] = that.project_user_achievement_end; //提交分数 0=未提交 1=提交
			

			hitmatchcommon.setProjectUserAchievementLibMethod(data); //提交分数

			that.ifpass = true; //弹出闯关1

		},
		//次数判断
		orderJudgment() {
			var that = this;
			var numberOfTests_a = that.level_data[that.grade]['numberOfTests']; //测试次数

			if (that.nowfrequency >= numberOfTests_a) {
				that.btn = that.btnb; //下一题
			} else {
				that.btn = that.btna; //下一关
			}
		},
		//下一题或者下一关
		gradeUp() {
			var that = this;
			//判断是否下一关
			that.judgeTheNextLevel();
		},
		//判断是否下一关
		judgeTheNextLevel() {
			var that = this;
			var number = that.level_data[that.grade]['numberOfTests']; //获取测试次数
			if (that.nowfrequency > number) {
				that.grade++;
				that.nowfrequency = 1; //当前次数重置
				that.thisLevelfraction = 0; //本关分数
				that.thisLeveltime = 0; //本关用时
			}
		},
		//点击判断
		clickList(e) {
			var that = this;
			//下一题或者下一关 btna: ['继续下一题', '返回关卡列表', '返回项目选择', '查看排行榜', '再次打榜'],
			if (e == 0) {
				//下一题或者下一关
				that.gradeUp();
				that.numberarr = []; //默认为空
				that.ifshow = true; //隐藏弹出遮罩
				that.ifpass = false; //关闭弹出
				that.selectgame(that.grade);
			}
			//返回关卡列表
			if (e == 1) {
				that.ifgame=true;
			}
			//返回项目选择
			if (e == '2') {
				uni.reLaunch({
					 url:hitmatchcommon.automaticurl('matcheslist')+"?id="+ Cache.get('project_make_id'),
				})
			}
			//排行榜
			if (e == '3') {
				 uni.reLaunch({
				 	url:hitmatchcommon.automaticurl('ranking')+"?id="+ Cache.get('project_make_id'),
				 })
			}
			//再次打榜
			if (e == 4) {
				that.numberarr = []; //默认为空
				that.nowfrequency = 1; //测试次数
				that.ifshow = true; //隐藏弹出遮罩
				that.ifpass = false; //关闭弹出
				that.selectgame(that.grade);
			}
			//提交分数
			if (e == '5') {
				//提交分数 0=未提交 1=提交
				that.project_user_achievement_end=1;
				that.submit();
				Base.publicshowtoastsuccess('提交成功',hitmatchcommon.automaticurl('matcheslist') + "?id=" + Cache.get('project_make_id'));
			}
		},

		//提交1
		confirmsubmit() {
			var that = this;
			uni.showModal({
				title: '提示',
				content: '确定提交吗？',
				success: function(res) {
					if (res.confirm) {
						that.submit(); //提交
						//时间结束1
						clearInterval(that.timer)
					} else if (res.cancel) {
						console.log('用户点击取消');
					}
				}
			});
		},
		//顺序是否正确与返回个数
		ranked() {
			var that = this;
			var gongGrid = that.level_data[that.grade]; //获取等级数据
			var grade = parseInt(gongGrid['num']);
			//判断顺序
			var ifsequence = 1; //0=顺序错误 1=顺序正常
			//判断存在数字
			var number = grade * grade;
			that.numberarr.forEach((item, index) => { //js遍历数组
				if (index <= number - 2) {
					if ((index + 1) != item) {
						ifsequence = 0; //0=顺序错误
					}
				}
			});
			that.first++; //增加次数
			if (ifsequence == '0') {
				return false;
			} else {
				return true; //
			}
		},
		//判断顺序正确个数
		determineTheNumberOfCorrectOrders() {
			var that = this;
			var p = 1;
			var numberQuestion = 0;
			try {
				that.numberarr.forEach((item, index) => { //js遍历数组
					//判断顺序加法
					if (p == item) {
						numberQuestion++;
					} else {
						throw Error('终止循环');
					}
					p++;
				});
			} catch (err) {
				return numberQuestion; //返回正确个数
			}
			return numberQuestion; //返回正确个数
		},
		//点击
		clicknumber(e) {
			var that = this;
			var nowindex = 0; //0的位置
			var ifmove = []; //可以移动数字
			//获取等级数据
			var gongGrid = that.level_data[that.grade];
			var grade = parseInt(gongGrid['num']);

			that.numberarr.forEach((item, index) => { //js遍历数组
				if (item == '0') {
					nowindex = index;
				}
			});
			//可以移动位置
			var nowtier = parseInt(nowindex / grade) + 1; //当前层数 3
			var mintier = (nowtier - 1) * grade; //最低层数 6
			var maxtier = nowtier * grade - 1; //最高层数 8
			console.log(nowindex);
			//前一个
			if (that.numberarr[nowindex - 1] && (nowindex - 1) >= mintier) {
				console.log("前一个" + that.numberarr[nowindex - 1]);
				ifmove.push(that.numberarr[nowindex - 1]);
			}
			//后一个
			if (that.numberarr[nowindex + 1] && (nowindex + 1) <= maxtier) {
				console.log("后一个" + that.numberarr[that.numberarr[nowindex + 1]]);
				ifmove.push(that.numberarr[nowindex + 1]);
			}
			//上一个
			if (that.numberarr[nowindex - grade]) {
				console.log("上一个" + that.numberarr[nowindex - grade]);
				ifmove.push(that.numberarr[nowindex - grade]);
			}
			//下一个
			if (that.numberarr[nowindex + grade]) {
				console.log("下一个" + that.numberarr[nowindex + grade]);
				ifmove.push(that.numberarr[nowindex + grade]);
			}
			console.log(ifmove);
			//可以移动 5 8 7
			if (ifmove.indexOf(e) > -1) {
				that.numberarr.forEach((item, index) => { //js遍历数组
					if (item == e) {
						//当前移动值
						that.numberarr[index] = 0;
						that.numberarr[nowindex] = e; //替换
					}
				});
			}
			//顺序正确
			if (that.ranked()) {
				that.submit(); //提交
				//时间结束1
				clearInterval(that.timer)
			}
		},
	}
}